package com.syzg.solr;

import java.util.Date;
import java.util.Map.Entry;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.syzg.common.config.MyProperties;
import com.syzg.common.exception.BaseException;
import com.syzg.common.util.PKCreator;
import com.syzg.common.util.SpringUtil;
import com.zenithsun.common.bean.SolrSearch;
import com.zenithsun.news.newsinfo.model.Newsinfo1;
import com.zenithsun.news.newsinfo.service.NewsinfoService;

/**
 * solr管理
 * @author 张学功
 *
 */
public class SolrManage {
	
	static Logger log = LoggerFactory.getLogger(SolrManage.class);
	static MyProperties procSolr = MyProperties.getInstance("solr.properties");

	public static void main(String[] args) {
		try {
			
			SpringUtil.initBySelf();
			NewsinfoService newsinfoService = (NewsinfoService)SpringUtil.getBean("newsinfoService");
			Newsinfo1 newsinfo1 = new Newsinfo1();
			newsinfo1.setId(PKCreator.getPk());
			newsinfo1.setTitle("世界人民大团结万岁");
			newsinfo1.setContent("中国人民站起来了，人民当家做主了");
			newsinfo1.setIsDelete((short)0);
			newsinfo1.setUpdateTime(new Date());
			newsinfoService.create(newsinfo1);
			dataImport("delta");
		} catch (Exception e) {
			log.error(BaseException.addExceptionLog(e));
		}
	}
	
	/**
	 * 全量更新数据
	 */
	public static void dataFullImport(){
		dataImport("full");
	}
	
	/**
	 * 增量更新数据
	 */
	public static void dataIncrementImport(){
		dataImport("delta");
	}
	
	/**
	 * 根据传入的增量处理类型来更新数据（full为全量更新，）
	 * @param importType
	 */
	private static void dataImport(String importType){
		String importUrl = null;
		String solrServerUrl = procSolr.getProperty("solrServer");
		if(importType.equals("full")){
			importUrl = solrServerUrl + procSolr.getProperty("fullImpUrl");
		} else {
			importUrl = solrServerUrl + procSolr.getProperty("deltaImpUrl");
		}
		String res = getHttpResponse(importUrl);
		log.info(res);
	}
	
	/**
	 * 创建服务
	 * @return
	 */
	public static SolrServer createSolrServer() {
		HttpSolrServer solr = null;
		try {
			String solrServerUrl = procSolr.getProperty("solrServer");
			solr = new HttpSolrServer(solrServerUrl);
			solr.setConnectionTimeout(100);
			solr.setDefaultMaxConnectionsPerHost(100);
			solr.setMaxTotalConnections(100);
		} catch (Exception e) {
			log.info("请检查tomcat服务器或端口是否开启!");
			e.printStackTrace();
		}
		return solr;
	}
	
	/**
	 * 调用并获取数据
	 * @param solrSearch
	 * @return QueryResponse
	 */
	public static QueryResponse Search(SolrSearch<?> solrSearch) {  
		SolrServer solrServer = createSolrServer();
        // 检测输入是否合法  
        SolrQuery query = null;
        try {
            // 初始化查询对象
            query = new SolrQuery(solrSearch.getSearchCondition());
            /*for (int i=0; i<field.length; i++){
                query.addFilterQuery(field[i] + ":" + key[i]);
            }*/
            // 设置起始位置与返回结果数
            query.setStart(solrSearch.getStart());
            query.setRows(solrSearch.getLimit());
            //设置排序信息
            if(solrSearch.getOrderMap()!=null&&solrSearch.getOrderMap().size()>0){
	            for(Entry<String,SolrQuery.ORDER> order:solrSearch.getOrderMap().entrySet()){
	            	query.addSort(order.getKey(), order.getValue());
	            }
            }
            // 设置高亮
            if (solrSearch.isHightlight()) {
                query.setHighlight(true); // 开启高亮组件
                query.addHighlightField("*");// 高亮字段
 //               query.addHighlightField("keywords");
                query.setHighlightSimplePre("<font color=\"red\">");// 标记
                query.setHighlightSimplePost("</font>");
                query.setHighlightSnippets(1);// 结果分片数，默认为1
                query.setHighlightFragsize(1000);// 每个分片的最大长度，默认为100
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        QueryResponse rsp = null;
        try {
            rsp = solrServer.query(query);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // 返回查询结果
        return rsp;
    }
	
	/**
	 * 远程调用solr服务
	 * @param args
	 * @return String
	 */
	public static String getHttpResponse(String args) {
		String res = null;
		byte[] responseBody = null;
		GetMethod getMethod = new GetMethod(args);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
		try {
			//发送Http请求
			HttpClient httpClient = new HttpClient();
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				throw new Exception("HTTP方法调用返回失败: " + getMethod.getStatusLine());
			}
			responseBody = getMethod.getResponseBody();			
			res = new String(responseBody,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return res;
	}
}
